<?php

namespace App\Http\Controllers\Resources;

use App\Models\AcceptRecord;
use App\Models\Customer;
use App\Models\Group;
use App\Models\Project;
use App\Models\User;
use App\Services\ServiceFactory;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Services\Interfaces\RepoServiceInterface;
use Auth;

class AcceptRecordController extends Controller
{
    public function __construct($_resource)
    {
        $this->_resource = $_resource;
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // 仅操作员可访问 TODO: 这一版只考虑账号最底层使用(社长和管家), 不考虑上级账号
        // 获取操作员负责的项目
        $user = Auth::User();
        // 当前用户负责的项目
        $project_ids = Project::whereIn('users', [$user->id])
            ->get()
            ->pluck('id')
            ->all();
        if (empty($project_ids)) {
            return $this->_error('此用户没有负责的项目');
        }
        $project_id = $project_ids[0];
        $data['customer_id'] = $request->input('customer_id');
        $data['company_id'] = $user->company_id;
        $data['user_id'] = $user->id;
        $data['project_id'] = $project_id;
        // 查询项目下是否存在传入客户
        $customer = Customer::find($data['customer_id']);
        if (!is_null($customer)) {
            $project_ids = $customer->projects;
            if (!in_array($project_id, $project_ids)) {
                return $this->_error('没有权限认领此客户');
            }
        } else {
            return $this->_error('此客户不存在');
        }
        // 如果存在符合认领条件的项目
        // 先判断此客户是否在此项目下被认领了
        $hasRecord = AcceptRecord::where(['project_id' => $data['project_id'],
            'customers' => $data['customer_id']])->first();
        if (!is_null($hasRecord)) {
            // 客户被认领, 获取认领人的姓名和手机, 在给个status = 1
            $userId = $hasRecord->user_id;
            $returnUser = User::find($userId);
            $name = $returnUser->name;
            $mobile = $returnUser->mobile;
            return $this->_error("st@,@".$name."@,@".$mobile);
        }
        $result = $this->_repoService()->create($data);
        return $result;
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $data = $request->all();
        // 表单校验
        if (empty($data['user']['from'] || empty($data['user']['to'])
                || empty($data['user']['type'])) || !in_array('customer_id', array_keys($data))) {
            return $this->_error("表单字段不能为空");
        }
        $from = $data['user']['from'];
        $to = $data['user']['to'];
        $type = $data['user']['type'];
        $customer_id = $data['customer_id'];
        // 判断$to账号是否被禁用
        $isTrue = User::find($to);
        if (!is_null($isTrue)) {
            $status = $isTrue->status;
            if ($status == 0) {
                return $this->_error("此账号被禁用");
            }
        } else {
            return $this->_error("账号不存在");
        }
        if ($type !== AcceptRecord::MV && $type !== AcceptRecord::CP) {
            return $this->_error('type字段有问题');
        }
        // 如果from和to两人负责的项目不一样, 则提示报错
        $project = Project::where('users', $from)->first();
        if (is_null($project)) {
            return $this->_error('此用户没有项目');
        }
        $users = $project->users;
        if (!in_array($to, $users)) {
            return $this->_error('两个人负责的项目不同');
        }
        $user = Auth::User();
        $group_id = $user->group_id;
        $group = new Group();
        $groups = $group->getLeafBy($group_id);
        // 是数组的话,说明是上级账号
        if (is_array($groups)) {
            // 此账号下面所有的项目id
            $project_ids = [];
            foreach ($groups as $v) {
                $project_id = Project::where('group_id', $v->id)->get()->pluck('id')->all();
                $project_ids = array_merge($project_ids, $project_id);
            }
            if (!in_array($project->id, $project_ids)) {
                return $this->_error('此账号的组织下没有该项目');
            }
        }
        
        $toUser = AcceptRecord::where(['user_id' => $to, 'project_id' => $project->id])->first();
        if (is_null($toUser)) {
            $acceptRecord = new AcceptRecord();
            $acceptRecord->company_id = $user->company_id;
            $acceptRecord->project_id = $project->id;
            $acceptRecord->user_id = $to;
            $acceptRecord->customers = [];
            $acceptRecord->save();
            $_filter = ['id' => $acceptRecord->id];
        } else {
            $_filter = ['id' => $toUser->id];
        }
        // 等于null,说明是改动from的所有客户
        $fromUser = AcceptRecord::where(['user_id' => $from, 'project_id' => $project->id])->first();
        $customers = $fromUser->customers;
        if (empty($customers)) {
            return $this->_error('此用户没有认领的客户');
        }
        if ($customer_id === null) {
            $data['customer_id'] = $customers;
            $isSave = $this->_repoService()->update($_filter, $data);
            if ($isSave) {
                return "modify success";
            } else {
                return $this->_error('操作失败');
            }
            // $toUser = AcceptRecord::where(['user_id' => $to, 'project_id' => $project->id])->first();
        } else {
            // customer_id不等于null, 说明是单个客户
            // 被转移的客户, 必须是$from认领过的客户
            if (!in_array($customer_id, $customers)) {
                return $this->_error("表单传递的customer_id不是from用户认领的客户");
            }
            $data['customer_id'] = array($customer_id);
            $isSave = $this->_repoService()->update($_filter, $data);
            if ($isSave) {
                return "modify success";
            } else {
                return $this->_error('操作失败');
            }
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
